﻿using NeuralStock.DataAccess;
using System.Linq.Expressions;
using System;

namespace NeuralStock.DomainService.Implementation
{
    public class BaseService
    {
        private const decimal decimalValuesComparisonPrecision = 0.1m;

        protected NeuralStockEntities DbContext = new NeuralStockEntities();

        protected decimal? SetNullabledecimal(string objectDescription, string propertyName, decimal? oldValue, decimal? newValue)
        {
            if (!newValue.HasValue)
            {
                return oldValue;
            }
            else if (!oldValue.HasValue)
            {
                return newValue;
            }
            else if (oldValue.Value == 0)
            {
                if (newValue.Value != 0)
                {
                    throw new InvalidOperationException(string.Format("Object:{0} Property: {1} OldValue: {2}, NewValue: {3}", objectDescription, propertyName, oldValue, newValue));
                }
            }
            else if ((newValue.Value / oldValue.Value - 1) > decimalValuesComparisonPrecision)
            {
                throw new InvalidOperationException(string.Format("Object:{0} Property: {1} OldValue: {2}, NewValue: {3}", objectDescription, propertyName, oldValue, newValue));
            }
            return newValue;
        }

        protected string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
        {
            var me = propertyLambda.Body as MemberExpression;
            return me.Member.Name;
        }
    }
}
